Page({
  data: {
    currentTab: 'all',
    activities: [
      // {
      //   id: 1,
      //   title: '拍照局',
      //   date: '2024.04.14',
      //   day: '周四',
      //   time: '19:00-21:00',
      //   fee: '无',
      //   location: '南山区深圳湾地铁站C出口'
      // }
    ],
     // 添加活动类型映射
     typeMap: {
      'all': '全部',
      'photo': '拍照',
      'travel': '旅行',
      'food': '美食',
      'sports': '运动',
      'movie': '电影',
      'study': '学习',
      'outdoor': '户外',
      'others': '其他'
    }
  },
  onShow() {
    // 加载用户的行程
    this.loadUserJourneys();
  },
  loadUserJourneys() {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity';
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        status: '1',       // 0-未开始, 1-进行中
        page: 1,
        page_size: 20
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 处理活动数据，转换格式
          const activities = res.data.data.activities.map(activity => {
            const startTime = new Date(activity.start_time);
            const endTime = new Date(activity.end_time);
           // 格式化日期
           const year = startTime.getFullYear();
           const month = String(startTime.getMonth() + 1).padStart(2, '0');
           const day = String(startTime.getDate()).padStart(2, '0');
           
           // 获取星期
           const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
           const weekDay = weekDays[startTime.getDay()];
           
           // 格式化时间
           const formatTime = (date) => {
             const hours = String(date.getHours()).padStart(2, '0');
             const minutes = String(date.getMinutes()).padStart(2, '0');
             return `${hours}:${minutes}`;
           };
           
           return {
             id: activity.id,
             title: activity.name,
             date: `${year}.${month}.${day}`,
             day: weekDay,
             time: `${formatTime(startTime)}-${formatTime(endTime)}`,
             fee: activity.fee || '无',
             location: activity.address,
             status: activity.status
           };
          });
          console.log(activities);

          this.setData({ activities });
        } else {
          wx.showToast({
            title: res.data.msg || '获取行程失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
    // 根据标签筛选活动
    this.filterActivities(tab);
  },

  filterActivities(tab) {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity';
    const requestData = {
      status: '1',       // 0-未开始, 1-进行中
      page: 1,
      page_size: 20
    };

    // 只有当不是 'all' 时才添加 type 参数
    if (tab !== 'all') {
      requestData.type = this.data.typeMap[tab];
    }

    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: requestData,
      success: (res) => {
        if (res.data.code === 200) {
          // 处理活动数据，转换格式
          const activities = res.data.data.activities.map(activity => {
            const startTime = new Date(activity.start_time);
            const endTime = new Date(activity.end_time);
          // 格式化日期
          const year = startTime.getFullYear();
          const month = String(startTime.getMonth() + 1).padStart(2, '0');
          const day = String(startTime.getDate()).padStart(2, '0');
          
          // 获取星期
          const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
          const weekDay = weekDays[startTime.getDay()];
          
          // 格式化时间
          const formatTime = (date) => {
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${hours}:${minutes}`;
          };
          
          return {
            id: activity.id,
            title: activity.name,
            date: `${year}.${month}.${day}`,
            day: weekDay,
            time: `${formatTime(startTime)}-${formatTime(endTime)}`,
            fee: activity.fee || '无',
            location: activity.address,
            status: activity.status
          };
          });

          this.setData({ activities });
        } else {
          wx.showToast({
            title: res.data.msg || '获取行程失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  joinGroup(e) {
    const { activityId } = e.currentTarget.dataset;
    // 先获取聊天室ID
    const websiteUrl = getApp().globalData.onlineService + '/api/chatroom/chatroom';
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        activity_id: activityId
      },
      success: (res) => {
        if (res.data.code === 200) {
          const chatGroupId = res.data.data.group_id;
          // 跳转到聊天页面
          wx.navigateTo({
            url: `/package_chat/pages/chat/chat?conversationID=GROUP${chatGroupId}`,
            fail: (err) => {
              wx.showToast({
                title: '进入聊天室失败',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取聊天室失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  openLocation(e) {
    const { location } = e.currentTarget.dataset;
    wx.openLocation({
      latitude: location.latitude,
      longitude: location.longitude,
      name: location.name,
      address: location.address
    });
  },
  
  goToHome() {
    wx.switchTab({
      url: '/pages/home/home',
    });
  }
});